package xyz.zyl2020.juc.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZhuYinglong
 * @date 2020/10/31 0031
 */
public class Demo01Lock {

    static final int ticketNum = 100;

    public static void main(String[] args) {
        SellTicket sellTicket = new SellTicket();
        new Thread(() -> {
            for (int i = 0; i < ticketNum; i++) {
                sellTicket.sell();
            }
        }, "A窗口").start();

        new Thread(() -> {
            for (int i = 0; i < ticketNum; i++) {
                sellTicket.sell();
            }
        }, "B窗口").start();

        new Thread(() -> {
            for (int i = 0; i < ticketNum; i++) {
                sellTicket.sell();
            }
        }, "C窗口").start();

    }

    static class SellTicket {
        private int num = ticketNum;
        private int count;
        private final Lock lock = new ReentrantLock();

        public void sell() {
            lock.lock();
            try {
                if (num <= 0) {
                    return;
                }
                System.out.println(Thread.currentThread().getName() + "\t卖出了第 " + (++count) + " 张票，剩余 " + (--num) + " 张！");
            } finally {
                lock.unlock();
            }

            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
